---
--- Created by tom.
--- DateTime: 2020/10/19 20:13
---
require "Common/functions"

--- @class Http
Http = {}

local HttpImpl = YanhuaMMO.Http;

--- url参数编码
--- @param s string 参数
--- @return string
function Http.UrlEncode(s)
    s = string.gsub(s, "([^%w%.%- ])", function(c)
        return string.format("%%%02X", string.byte(c))
    end)
    return string.gsub(s, " ", "+")
end

--- url参数解码
--- @param s string 参数
--- @return string
function Http.UrlDecode(s)
    s = string.gsub(s, '%%(%x%x)', function(h)
        return string.char(tonumber(h, 16))
    end)
    return s
end

--- url拼接参数
--- @param url string 请求地址
--- @param params table 参数表
--- @return string
function Http.AppendUrlParams(url, params)
    if type(params) == "table" then
        local first = true
        local queryStr = ""
        for key, value in pairs(params) do
            if value == nil then
                value = ''
            end
            if type(value) == 'table' then
                value = getJsonStr(value)
            end
            if first then
                queryStr = queryStr .. key .. '=' .. Http.UrlEncode(value)
                first = false
            else
                queryStr = queryStr .. "&" .. key .. '=' .. Http.UrlEncode(value)
            end
        end
        params = queryStr
    end

    if params and params ~= "" then
        url = url .. ('&' and string.find(url, '?') ~= nil or '?') .. params
    end

    return url
end

--- 将字典参数的值格式化为字符串
--- @param params table 请求地址
--- @return table
function Http.StringifyParams(params)
    if type(params) == "table" then
        for key, value in pairs(params) do
            if value == nil then
                value = ''
            end
            if type(value) == 'table' then
                value = getJsonStr(value)
            else
                value = tostring(value)
            end
            params[key] = value
        end
    end

    return params
end

--- Get请求字符串
--- @param url string 请求地址
--- @param params table 请求参数字典. KVP<string, string>格式，拼接成url参数。
--- @param callback fun(success: boolean, ret: string) 回调函数。function(bool, ret)
--- @param headers table<string, string> 自定义头。默认为空
function Http.Get(url, params, callback, headers)
    url = Http.AppendUrlParams(url, params)
    if headers then
        HttpImpl.Get(url, {}, callback, headers)
    else
        HttpImpl.Get(url, {}, callback)
    end
end

--- Post请求
--- @param url string 请求地址
--- @param params table|string 请求数据字典或者字符串。
--- @param callback fun(success: boolean, ret: string) 回调函数。function(bool, ret)
--- @param headers table<string, string> 自定义头。默认为空
function Http.Post(url, params, callback, headers)
    if headers then
        HttpImpl.Post(url, Http.StringifyParams(params), callback, headers)
    else
        HttpImpl.Post(url, Http.StringifyParams(params), callback)
    end
end

return Http